package waveAlgorithm.control;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import waveAlgorithm.entity.Process;

/**
 * @since Oct 17, 2011
 * @author <a href="mailto:zexpp5@gmail.com">Zexu.Lin</a>
 * @version $Id: Controler.java 30 2011-10-30 10:52:47Z zexpp5@gmail.com $
 * 
 */
public class Controler {
	public static int numEnd;
	private static Logger logger = Logger.getLogger(Controler.class);

	static {
		DOMConfigurator.configure(Controler.class
				.getResource("../../distributedalgorithm.log4j.xml"));
	}

	public static void main(String[] args) {
		int sw;
		if (args == null) {
			 sw= 0;
		} else {
			 sw = Integer.parseInt(args[0]);
		}
		
		for (int i = 0; i < 900; i++) {
			numEnd = 0;
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			logger.warn("=======================Iteration started=======================");

			HashMap<String, Thread> threads = new HashMap<String, Thread>();

			int n = (int) (Math.random() * 10);
			if (n < 2) {
				continue;
			}
			HashMap<String, Process> processes = null;
			switch (sw) {
			case 1:
				processes = Initiator.initRandomly(n);

				break;
			case 2:
				processes = Initiator.initBalancedBinaryTree();

				break;
			case 3:
				processes = Initiator.initUnBalancedBinaryTree();

				break;
			default:
				processes = Initiator.initRandomly(n);
				break;
			}
			// HashMap<String, Process> processes = Initiator.initRandomly(n);
			// HashMap<String, Process> processes = Initiator
			// .initBalancedBinaryTree();
			// HashMap<String, Process> processes = Initiator
			// .initUnBalancedBinaryTree();

			Iterator it = processes.entrySet().iterator();

			while (it.hasNext()) {

				Map.Entry<String, Process> entryProcesses = (Map.Entry<String, Process>) it
						.next();

				threads.put(entryProcesses.getKey(),
						new Thread(entryProcesses.getValue()));

			}

			logger.warn("Threads ready.");

			it = threads.entrySet().iterator();

			Thread t = null;

			while (it.hasNext()) {

				Map.Entry<String, Thread> entryThreads = (Map.Entry<String, Thread>) it
						.next();

				t = entryThreads.getValue();

				t.start();

				logger.info(entryThreads.getKey() + "    started.");

			}
			logger.warn("All threads started.");

			while (numEnd != n) {
			}

			logger.warn("=======================Iteration ended=======================");

		}
	}
}
